<?php
/**
 * Copyright 2011  SURFfoundation
 * 
 * This file is part of ESCAPE.
 * 
 * ESCAPE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * ESCAPE is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with ESCAPE.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * For more information:
 * http://escapesurf.wordpress.com/
 * http://www.surffoundation.nl/
 * 
 * Contact: d.vierkant@utwente.nl
 * 
 * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3
 */
?>
<?php
/**
 * Edit
 * 
 * Edit an object.
 */
class escape_repositoryui_action_Edit extends escape_repositoryui_Action
{
	public function handleRequest()
	{
		/* @var $repository escape_repository_Repository */
		$repository =& $this->requestAttributes['repository'];
		/* @var $repositoryUi escape_repositoryui_RepositoryUi */
		$repositoryUi =& $this->requestAttributes['repositoryUi'];
		
		$gadgetModeUrlParameter = '';
		if($repositoryUi->isGadgetMode())
		{
			$gadgetModeUrlParameter = '?gadget=1';
		}
		
		// fetch the ID from the request
		$objectId = $_REQUEST['actionValue'];
		$objectUri = $repository->convertDataObjectIdToObjectUri($objectId);
		
		$aggregation = null;
		try {
			$oreObject = $repository->getOreObjectByUri($objectUri);
			$this->requestAttributes['oreObject'] =& $oreObject;
		}
		catch(Exception $exception)
		{
			$repositoryUi->displayErrorPage($exception->getMessage());
			return null;
		}
		$aggregation = $oreObject->getAggregation();
		$this->requestAttributes['aggregation'] =& $aggregation;
		
		// add a breadcrumb for this object
		// link it to the show page instead of the editor 
		$breadCrumb = new escape_repositoryui_BreadCrumb();
		$breadCrumb->setTitle($oreObject->getTitle());
		$breadCrumb->setUrl('/show/' . $oreObject->getId());
		$repositoryUi->addBreadCrumb($breadCrumb);
		
		// check if the user is authorized to edit this object
		$user = $repositoryUi->getUser();
		$userIsAuthorized = false;
		if($user)
		{
			$userUri = $user->getUri();
			if($user->hasSystemRole(escape_repository_User::$role_administrator) || $aggregation->hasEditor($userUri) || $aggregation->hasOwner($userUri))
			{
				$userIsAuthorized = true;
			}
		}
	
		if(!$userIsAuthorized)
		{
			// user is not authorized to edit this resource, redirect to login page
			$repositoryUi->redirectToLoginForAction($this->requestAttributes['actionName'], $objectId);
			return null;
		}

		return 'ObjectEdit';
	}
}